package parse;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Arrays;

import data.Player;
import data.TournamentList;

public class TournamentParser {

	private String fileName = null;
	
	public TournamentParser (String aFileName){
		fileName = aFileName;
	}
	
	public TournamentList parse(){
		TournamentList res = new TournamentList();
		
		FileInputStream fis = null;
		BufferedReader reader = null;
		String line;
		
		try{
			fis = new FileInputStream(fileName);
			reader = new BufferedReader(new InputStreamReader
					(fis, Charset.forName("UTF-8")));
			
			while ((line = reader.readLine()) != null) {
				Player p = parseLine (line);
				if (p != null){
					res.addPlayer (p);
				}				
			}
			reader.close();
		} catch (IOException io){			
			reader = null;
			fis = null;
			io.printStackTrace ();
		}								
		return res;
	}
	
	private Player parseLine(String line){
		String[] tmp = line.split(" ");
		if (tmp.length < 1){
			return null;
		}
		Player res = new Player(tmp[0]);
		for (int i = 1; i < tmp.length; i++){
			res.addPoints (Double.parseDouble (tmp[i]));
		}				
		return res;
	}
}
